package org.example.gateway.controller;

import org.example.gateway.pojo.ChangeStatusDto;
import org.example.gateway.pojo.RuleDto;
import org.example.gateway.pojo.vo.CommonResult;
import org.example.gateway.pojo.vo.RuleVo;
import org.example.gateway.service.RuleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/rule")
public class RuleController {

    @Resource
    private RuleService ruleService;

    /**
     * add new route rule
     *
     * @param dto
     * @return
     */
    @PostMapping("")
    public CommonResult add(@Validated RuleDto dto){
        ruleService.add(dto);
        return CommonResult.success();
    }

    @DeleteMapping("/{id}")
    public CommonResult delete(@PathVariable("id") Integer id) {
        ruleService.delete(id);
        return CommonResult.success();
    }

    @GetMapping("/list")
    public ModelAndView list(ModelMap map, @RequestParam(name = "appName", required = false) String appName) {
        List<RuleVo> ruleVos= ruleService.queryList(appName);
        map.put("ruleVOS", ruleVos);
        map.put("appName", appName);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/rule.html");
        modelAndView.addAllObjects(map);
        return modelAndView;
    }

    @PutMapping("/status")
    public CommonResult changeStatus(@RequestBody ChangeStatusDto dto) {
        ruleService.changeStatus(dto);
        return CommonResult.success();
    }
}
